package edu.chl.food_store.beans.control;

import edu.chl.food_store.beans.backing.RegisterBackingBean;
import edu.chl.food_store.beans.ejb.CustomerEJB;
import edu.chl.food_store.entities.Customer;
import edu.chl.food_store.entities.Address;
import java.io.Serializable;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.*;
import javax.faces.context.FacesContext;

/**
 * RegisterControllerBean:
 * Controller bean for registering users.
 */
@ManagedBean
@RequestScoped
public class RegisterControllerBean implements Serializable {

    @EJB
    private CustomerEJB userEjb;
    @ManagedProperty(value = "#{registerBackingBean}")
    private RegisterBackingBean registrationData;

    /**
     * Try to register a new user. 
     */
    public void registerCustomer() {
        Customer customer = null;
        String fname = registrationData.getFname();
        String lname = registrationData.getLname();
        String email = registrationData.getEmail();
        String password = registrationData.getPassword();
        String street = registrationData.getStreet();
        String city = registrationData.getCity();
        String country = registrationData.getCountry();
        FacesMessage msg = null;
        //Check if no other customer has the same e-mail
        customer = userEjb.findCustomerByEmail(email);
        //If someone else hase the same e-mail, tell the use and return.
        if (customer != null) {
            msg = new FacesMessage(FacesMessage.SEVERITY_ERROR, "Customer E-mail already exist!", "");
            FacesContext.getCurrentInstance().addMessage(null, msg);
        } else {
            Address address = new Address(street, city, country);
            customer = new Customer(fname, lname, email, password, address);
            //Add a new customer in the database
            if (userEjb.createCustomer(customer)) {
                //If the customer was succesfully registered, send message and return to main.
                msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "You have been registered!", "");
                FacesContext.getCurrentInstance().addMessage(null, msg);
            }
        }
    }

    public RegisterBackingBean getRegistrationData() {
        return registrationData;
    }

    public void setRegistrationData(RegisterBackingBean registrationData) {
        this.registrationData = registrationData;
    }
}
